<template>
  <div class="notice-admin-container">
    <!-- 标题和操作按钮 -->
    <div class="header-section">
      <h2>公告管理</h2>
      <el-button
          type="primary"
          @click="beforeAddNotice"
          style="background-color: #409EFF; border-color: #409EFF;"
      >
        <el-icon><Plus /></el-icon>
        发布公告
      </el-button>
    </div>

    <!-- 搜索卡片 -->
    <el-card class="search-card" shadow="hover">
      <el-form :inline="true">
        <el-form-item label="公告标题">
          <el-input placeholder="请输入公告标题" v-model="searchForm.title" clearable></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="草稿" :value="0"></el-option>
            <el-option label="已发布" :value="1"></el-option>
            <el-option label="已撤回" :value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button @click="resetSearch">重置</el-button>
          <el-button type="primary" @click="handleSearch" style="background-color: #409EFF; border-color: #409EFF;">搜索</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 公告表格卡片 -->
    <el-card class="table-card" shadow="hover">
      <el-table
          :data="noticeArr"
          border
          stripe
          style="width: 100%"
          v-loading="loading"
      >
        <el-table-column type="index" label="序号" width="80" align="center"></el-table-column>
        <el-table-column prop="title" label="标题" min-width="180" show-overflow-tooltip></el-table-column>
        <el-table-column prop="publisherId" label="发布人ID" width="120" align="center"></el-table-column>
        <el-table-column prop="status" label="状态" width="100" align="center">
          <template #default="{row}">
            <el-tag :type="statusTagType(row.status)">
              {{ statusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="publishTime" label="发布时间" width="180" align="center">
          <template #default="{row}">
            {{ formatDateTime(row.publishTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="expireTime" label="过期时间" width="180" align="center">
          <template #default="{row}">
            {{ formatDateTime(row.expireTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="220" align="center" fixed="right">
          <template #default="{row}">
            <el-button
                size="small" @click="showDetail(row)" plain>
              详情
            </el-button>
            <el-button
                size="small" type="primary" @click="editNotice(row)" plain>
              编辑
            </el-button>
            <el-button
                size="small" type="danger" @click="deleteNotice(row.noticeId)" plain>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
            v-model:current-page="pagination.current"
            v-model:page-size="pagination.size"
            :total="pagination.total"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 公告编辑对话框 -->
    <el-dialog
        v-model="dialogVisible"
        :title="dialogTitle"
        width="50%"
    >
      <el-form
          :model="saveNoticeForm"
          label-width="100px"
          ref="noticeFormRef"
          :rules="noticeRules"
      >
        <el-form-item label="公告标题" prop="title">
          <el-input
              v-model="saveNoticeForm.title"
              placeholder="请输入公告标题"
          />
        </el-form-item>
        <el-form-item label="公告内容" prop="content">
          <el-input
              type="textarea"
              :rows="8"
              v-model="saveNoticeForm.content"
              placeholder="请输入公告内容"
          />
        </el-form-item>
        <el-form-item label="发布范围" prop="scope">
          <el-radio-group v-model="saveNoticeForm.scope">
            <el-radio :label="1">全部</el-radio>
            <el-radio :label="2">指定区域</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="过期时间" prop="expireTime">
          <el-date-picker
              v-model="saveNoticeForm.expireTime"
              type="datetime"
              placeholder="选择过期时间"
              value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="saveNoticeForm.status">
            <el-radio :label="0">草稿</el-radio>
            <el-radio :label="1">发布</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button
            type="primary"
            @click="saveNotice"
            style="background-color: #409EFF; border-color: #409EFF;"
        >
          保存
        </el-button>
      </template>
    </el-dialog>

    <!-- 公告详情对话框 -->
    <el-dialog
        v-model="detailDialogVisible"
        title="公告详情"
        width="50%"
    >
      <el-descriptions :column="1" border>
        <el-descriptions-item label="公告ID">{{ currentNotice.noticeId }}</el-descriptions-item>
        <el-descriptions-item label="标题">{{ currentNotice.title }}</el-descriptions-item>
        <el-descriptions-item label="发布人ID">{{ currentNotice.publisherId }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="statusTagType(currentNotice.status)">
            {{ statusText(currentNotice.status) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="发布时间">{{ formatDateTime(currentNotice.publishTime) }}</el-descriptions-item>
        <el-descriptions-item label="过期时间">{{ formatDateTime(currentNotice.expireTime) }}</el-descriptions-item>
        <el-descriptions-item label="发布范围">
          {{ scopeText(currentNotice.scope) }}
        </el-descriptions-item>
        <el-descriptions-item label="内容">
          <div class="notice-content">
            {{ currentNotice.content }}
          </div>
        </el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import {
  ElMessage,
  ElMessageBox
} from "element-plus";
import {
  Plus
} from '@element-plus/icons-vue';
import axios from "axios";
import dayjs from 'dayjs';

const BASE_URL = 'http://localhost:8080/api/v1/admins';

const noticeFormRef = ref(null);

// 当前登录管理员信息
const currentAdmin = ref({
  id: null,
  username: ''
});

// 搜索表单
const searchForm = ref({
  title: '',
  status: null
})

// 分页信息
const pagination = ref({
  current: 1,
  size: 10,
  total: 0
})

// 加载状态
const loading = ref(false)

// 公告列表数据
const noticeArr = ref([])

// 详情对话框
const detailDialogVisible = ref(false)
const currentNotice = ref({})

// 编辑对话框
const dialogVisible = ref(false)
const dialogTitle = ref('发布公告')
const saveNoticeForm = ref({
  noticeId: null,
  title: '',
  content: '',
  publisherId: null,
  publishTime: '',
  expireTime: '',
  status: 1,
  scope: 1,
  createTime: '',
  updateTime: '',
})

// 表单验证规则
const noticeRules = {
  title: [
    {required: true, message: '请输入标题', trigger: 'blur'},
    {min: 5, max: 50, message: '长度在5到50个字符', trigger: 'blur'}
  ],
  content: [
    {required: true, message: '请输入内容', trigger: 'blur'},
    {min: 10, message: '内容至少10个字符', trigger: 'blur'}
  ],
  scope: [
    {required: true, message: '请选择发布范围', trigger: 'change'}
  ],
  expireTime: [
    {required: true, message: '请选择过期时间', trigger: 'change'}
  ],
  status: [
    {required: true, message: '请选择状态', trigger: 'change'}
  ]
}

// 状态文本映射
const statusText = (status) => {
  const map = {
    0: '草稿',
    1: '已发布',
    2: '已撤回'
  }
  return map[status] || '未知'
}

// 状态标签类型
const statusTagType = (status) => {
  const map = {
    0: 'info',
    1: 'success',
    2: 'warning'
  }
  return map[status] || 'info'
}

// 发布范围文本
const scopeText = (scope) => {
  const map = {
    1: '全部',
    2: '指定区域'
  }
  return map[scope] || '未知'
}

// 日期格式化
const formatDateTime = (date) => {
  return date ? dayjs(date).format('YYYY-MM-DD HH:mm:ss') : '-'
}

// 获取当前登录管理员信息
const getCurrentAdmin = () => {
  const user = JSON.parse(localStorage.getItem('user'));
  if (user) {
    currentAdmin.value = {
      id: user.userId,
      username: user.username
    };
  }
}

// 获取公告列表 - 修改后的方法
const fetchNoticeList = async () => {
  try {
    loading.value = true;
    const params = {
      pageNum: pagination.value.current,
      pageSize: pagination.value.size,
      // 移除搜索条件，先确保基础查询能工作
      // title: searchForm.value.title,
      // status: searchForm.value.status
    };

    console.log('请求参数:', params); // 调试用

    const response = await axios.get(`${BASE_URL}/notice/list`, { params });
    console.log('响应数据:', response.data); // 调试用

    if (response.data.code === 2000) {
      // 确保数据结构匹配
      if (response.data.data && response.data.data.list) {
        noticeArr.value = response.data.data.list;
        pagination.value.total = response.data.data.total || 0;
      } else if (Array.isArray(response.data.data)) {
        // 如果返回的是数组而不是分页对象
        noticeArr.value = response.data.data;
        pagination.value.total = response.data.data.length;
      } else {
        noticeArr.value = [];
        pagination.value.total = 0;
        ElMessage.warning('公告列表为空');
      }
    } else {
      ElMessage.error(response.data.msg || '获取公告列表失败');
    }
  } catch (error) {
    console.error('获取公告列表失败:', error);
    let errorMsg = '获取公告列表失败，请检查网络连接';
    if (error.response) {
      errorMsg = error.response.data?.msg || errorMsg;
    }
    ElMessage.error(errorMsg);
  } finally {
    loading.value = false;
  }
}

// 搜索
const handleSearch = () => {
  pagination.value.current = 1;
  fetchNoticeList();
}

// 重置搜索
const resetSearch = () => {
  searchForm.value = {
    title: '',
    status: null
  };
  handleSearch();
}

// 分页大小变化
const handleSizeChange = (size) => {
  pagination.value.size = size;
  fetchNoticeList();
}

// 当前页变化
const handleCurrentChange = (current) => {
  pagination.value.current = current;
  fetchNoticeList();
}

// 新增公告
const beforeAddNotice = () => {
  dialogTitle.value = '发布公告';
  saveNoticeForm.value = {
    noticeId: null,
    title: '',
    content: '',
    publisherId: currentAdmin.value.id,
    publishTime: new Date().toISOString(),
    expireTime: dayjs().add(7, 'day').format('YYYY-MM-DD HH:mm:ss'),
    status: 1,
    scope: 1,
    createTime: new Date().toISOString(),
    updateTime: new Date().toISOString(),
  };
  dialogVisible.value = true;
}

// 显示详情
const showDetail = (row) => {
  currentNotice.value = row;
  detailDialogVisible.value = true;
}

// 编辑公告
const editNotice = (row) => {
  dialogTitle.value = '编辑公告';
  saveNoticeForm.value = {
    ...row,
    publisherId: currentAdmin.value.id,
    updateTime: new Date().toISOString()
  };
  dialogVisible.value = true;
}

// 保存公告
const saveNotice = async () => {
  try {
    await noticeFormRef.value.validate();

    saveNoticeForm.value.publisherId = currentAdmin.value.id;
    saveNoticeForm.value.updateTime = new Date().toISOString();

    if (!saveNoticeForm.value.noticeId) {
      saveNoticeForm.value.createTime = new Date().toISOString();
      saveNoticeForm.value.publishTime = saveNoticeForm.value.status === 1 ? new Date().toISOString() : null;
    } else {
      if (saveNoticeForm.value.status === 1 && !saveNoticeForm.value.publishTime) {
        saveNoticeForm.value.publishTime = new Date().toISOString();
      }
    }

    const url = saveNoticeForm.value.noticeId
        ? `${BASE_URL}/notice/update`
        : `${BASE_URL}/notice/add`;

    const response = await axios.post(url, saveNoticeForm.value);

    if (response.data.code === 2000) {
      ElMessage.success('保存成功!');
      dialogVisible.value = false;
      fetchNoticeList();
    } else {
      ElMessage.error(response.data.msg || '保存失败');
    }
  } catch (error) {
    console.error('请求失败:', error);
    ElMessage.error(error.response?.data?.msg || '保存失败');
  }
}

// 删除公告
const deleteNotice = async (noticeId) => {
  try {
    await ElMessageBox.confirm('确定删除该公告吗?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    const response = await axios.post(`${BASE_URL}/notice/delete`, [noticeId])
    if (response.data.code === 2000) {
      ElMessage.success('删除成功!')
      fetchNoticeList()
    } else {
      ElMessage.error(response.data.msg || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败: ' + error.message)
    }
  }
}

// 初始化加载数据
onMounted(() => {
  getCurrentAdmin();
  fetchNoticeList();
})
</script>

<style scoped>
.notice-admin-container {
  padding: 20px;
  background-color: #f5f7fa;
  height: 100%;
}

.header-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-section h2 {
  color: #304156;
  font-size: 20px;
  font-weight: 600;
}

.search-card {
  margin-bottom: 20px;
  border-radius: 4px;
  border: none;
  background-color: #fff;
}

.table-card {
  border-radius: 4px;
  border: none;
  background-color: #fff;
}

.el-table {
  width: 100%;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.notice-content {
  white-space: pre-wrap;
  line-height: 1.6;
  padding: 8px;
  background-color: #f8f9fa;
  border-radius: 4px;
}

.el-descriptions-item {
  padding: 12px 0;
}

.el-descriptions-item :deep(.el-descriptions__label) {
  width: 120px;
  color: #909399;
}

.el-descriptions-item :deep(.el-descriptions__content) {
  color: #304156;
}
</style>